CN.record = "个议程";
var msg=CN;
var schedule = {edit_status:"create",uid:site.uid,gids:[],guestbox:[],pesid:0,spids:[],sponsorbox:[]};
$(function(){
	init();
	mpage.modalfactory = function(data,position){//生成列表内容 //TODO 需要变化的地方
        $(".tablist").empty();
        tablist.position = position;//设置数据所在位置
        var tdValue =  "",
            rowclass = "",
            td = function(arg){
            	if(!arg)arg = "-";
            return "<td>"+arg+"</td>";           
            },
            get_length =  function(st){
            	if(st){
	            	var arg = st.split(',');
	            	return arg.length;
            	}
            	return 0;
            },
            setnum = function(arg){
            	var color = {current:"",c1:"label-info",c2:"label-success"};
            	switch(arg){
	            	case "1":color.current = color.c1;break;
	            	case "2":color.current = color.c2;break;
            	}
            	return "<span class='label "+color.current+"'>"+arg+"<span>";
            },
            setButton = function(data){
            	var btns = '<div class="btn-group" data-toggle="buttons-radio">';
            	btns += "<a class='btn btn-info btn-mini' onclick='del(this)' data-name='"+data.title+"' data-id='"+data.esid+"'>移除</a>";
            	btns += "<a class='btn btn-info btn-mini' onclick='getmore(this)' data-name='"+data.title+"' data-id='"+data.esid+"' status='0' view='off'>展开</a>";
            	btns += "</div>";
            	return btns;
            },
            settitle = function(data){
            	return '<button class="btn btn-info btn-mini" onclick="get(this)" type="button"  data-id="'+data.esid+'">'+data.title+'</button>';
            };
        for ( var element in data) {
        	var kk =data[element],
             	tdValue =td(setnum(kk.num))+ 
            	td(settitle(kk))+
            	td(kk.subtitle)+ 
            	td(timeformat(kk.startdate,4)+"~"+timeformat(kk.enddate,4))+
            	td(kk.desc)+
            	td(get_length(kk.gids))+
             	td(timeformat(kk.addtime))+
             	td(setButton(kk));
               	rowclass = element%2;//行样式
               $(".tablist").append("<tr class='tr"+rowclass+"'>"+tdValue+"</tr>");
        }
    };
    mpage.setext("?eid="+getUrlParam("eid"));
	mpage.init();
}); 

function init(){
	init_dialog();
	init_datepicker();
	init_guest_dialog();
}

init_datepicker = function(){
	$(".form_date").datetimepicker({format: 'yyyy/mm/dd hh:ii',todayBtn: true,autoclose: true});
}
init_dialog = function(){
	create_sub_schedule = function(arg){//create sub schedule
		var pesid = $(arg).attr("pesid");
		schedule.pesid = pesid;
		schedule.edit_status = "create";
		open_dialog();
	}
	$("#dialog_create").click(function(){//create & open dialog
		schedule.edit_status = "create";
		schedule.pesid = 0;//默认为父议程 20130730 
		open_dialog();
	});
	$("#dialog_save").click(function(){//save schedule
		$(this).attr("disabled",true);
		$(".dialogmsg").text("执行操作中...");
		schedule.title = $("#title").val();
		schedule.subtitle = $("#subtitle").val();
		schedule.num = $("#num").val();
		schedule.desc = $("#desc").val();
		var dat = {start:new Date($("#startdate").val()),end:new Date($("#enddate").val())};
		schedule.begindate = dat.start.getTime()/1000;
		schedule.startdate = schedule.begindate;
		schedule.enddate = dat.end.getTime()/1000;
		schedule.uid = site.uid;
		schedule.url = site.web+"my/"+site.title+"/"+schedule.edit_status;//包含create/update操作
		schedule.eid = getUrlParam("eid");
		schedule.esid = $("#esid").val();

		if(schedule.edit_status=="update"){
			//获取场地,场地描述信息
			$('#venueselect option').each(function(){
				schedule.venueid = $('option:selected').val();
				schedule.venuedesc = $('option:selected').attr("desc");
			});
		}
		complete = function(data){
			done_method = function(){
				$('#myModal').modal('hide');
				mpage.init();
			};
			if(data.code==1){
				$(".dialogmsg").text("操作成功!");
				setTimeout(done_method, 2000);				
			}else{
				$('#myModal').modal('hide');
			}
			
		}
		G(schedule,complete);
	});
	$(".canceldialog").click(function(){//cancel
		clear_dialog();
		$('#myModal').modal('hide');
	});
}

clear_dialog = function(){
	$("#form1 input[type=reset]").click();
	$("#dialog_save").attr("disabled",false);
	$(".venuelist").empty();
	$(".dialogmsg").text("");
}

open_dialog = function(data){
	clear_dialog();
	var eid = getUrlParam("eid");
	switch(schedule.edit_status){
		case "create":
			$(".dialog_status").text("新增");
			getvenue(eid,"add");//获取场地
			resetbox();
			showguest();
			break;
		case "update":
			$(".dialog_status").text("更新");
			var venueid = {name:"venueid",id:""};
			$.each(data, function(index, value) {
				if(index =="startdate" || index == "enddate"){
					$("#"+index).val(timeformat(value,8));
				}else{
					$("#"+index).val(value);
					if(index==venueid.name)
						venueid.id = value;
				}
				//if(index !="eid" && index !="uid" && index !="gids" && index !="venueid" && index !="venuedesc"){ }
			});
			getvenue(eid,"edit",venueid.id);//获取并设置场地
			$(".guestlist").empty();
			getguest(data.gids);//设置嘉宾
			getsponsor(data.esmvalue);//设置赞助商
			schedule.pesid = data.pesid;//set pesid
			break;
	}
	$('#myModal').modal('show');
}

get = function(arg){
	var id = $(arg).attr("data-id");
	cb = function (data){
		if(data.code==1){
			if(data.data.length==1){
				schedule.edit_status = "update";
				open_dialog (data.data[0]);
			}
		}else{
			alert("ERROR schedule 404");
		}
	}
	var url = site.web+"my/"+site.title+"/get";
	var json = {url:url,esid:id,uid:site.uid};
	G(json,cb);
}

del = function(arg){
	var name =  $(arg).attr("data-name");
	if(confirm("确认移除"+name+"?")==false)return;
	var id = $(arg).attr("data-id");
	cb = function (data){
		mpage.init();
	}
	var url = site.web+"my/"+site.title+"/del";
	var json = {url:url,esid:id,uid:site.uid};
	G(json,cb);
}

getmore = function(arg){
	var status 	= $(arg).attr("status"),
		id 		= $(arg).attr("data-id"),
		name 	= $(arg).attr("data-name"),
		view 	= $(arg).attr("view"),
		eid 	= getUrlParam("eid");
	switch(view){
	 	case "off":
	 		$(arg).text("隐藏");
	 		$(arg).attr("view","on");
	    	if(status=="0"){
	    		$(arg).attr("status","1");
		        var html = "<tr class='newrow'><td colspan='9' id='td"+id+"'>数据获取中...</td></tr>";
		        $(arg).parent().parent().parent().after(html);
		        //获取所有子会议
		    	cb = function (data){
		    		getinfo(id,name,data.data);
		    	}
		    	var url = site.web+"my/"+site.title+"/list";
		    	var json = {url:url,pesid:id,uid:site.uid,eid:eid};
		    	G(json,cb);
	    	}else{
	    		$(arg).parent().parent().parent().next().show();
	    	}
	    	break;
	 	case "on":
	 		$(arg).text("展开");
	 		$(arg).parent().parent().parent().next().hide();
	 		$(arg).attr("view","off");
	 		break;
	}		
}

getinfo = function(id,name,data){
	var addbtn = "<a class='btn btn-success btn-mini right' pesid='"+id+"' onclick='create_sub_schedule(this)'>增加"+name+"的子议程</a>";
	if(data.length==0){
		$("#td"+id).html("没有子议程"+addbtn);
	}else{
		td = function(arg,type){
			if(!arg)arg="-";
			if(type=="lab"){
				return "<td><span class='label'>"+arg+"</span></td>";
			}
			return '<td>'+arg+'</td>';
			}
		tr = function(arg){return '<tr><td colspan="9">'+arg+'</td></tr>';}
		item = function(arg,it){
			return '<'+it+'>'+arg+'</'+it+'>';
		}
		tab = function(arg){
			return "<table  class='table table-hover table-bordered'>"+arg+"</table>";
		}
		var thead = "<tr>"+td("排序","lab")+td("议程","lab")+td("主题","lab")+td("举行时间","lab")+td("描述","lab")+td("嘉宾人数","lab")+td("创建时间","lab")+td("操作")+"</tr>",
			tfoot = tr(addbtn),
			tbody = "",
			get_length =  function(st){
		     	if(st){
		         	var arg = st.split(',');
		         	return arg.length;
		     	}
		     	return 0;
		    },
		    updatetitle = function(data){
		    	return "<a class='btn btn-info btn-mini' onclick='get(this)' data-id='"+data["esid"]+"'>"+data["title"]+"</a>";
		    },
		    menu = function(data){
		    	return "<a class='btn btn-danger btn-mini' onclick='del(this)' data-id='"+data["esid"]+"' data-name='"+data["title"]+"'>移除</a>";
		    };
		//TODO vincent !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		for(var key in data){
			var kk = data[key];
			var tr = td(kk["num"])+
				td(updatetitle(kk))+
				td(kk["subtitle"])+
				td(timeformat(kk["startdate"])+"~"+timeformat(kk["enddate"]))+
				td(kk["desc"])+
				td(get_length(kk["gids"]))+
				td(timeformat(kk["addtime"]))+
				td(menu(kk));
			tbody += "<tr>"+tr+"</tr>";
		}
		$("#td"+id).html(tab(item(thead+tfoot,"thead")+item(tbody,"tbody")+item(tfoot,"tfoot")));
	}
}

getvenue = function(id,status,selectid){//venue
	cb = function (data){
		if(data.code==1){
			var list = "<select id='venueselect'>";
			if(status=="add")
				list += "<option value='' desc=''>请选择场地</option>";
			for(var key in data.data){
				var id = data.data[key]['evid'],
					name = data.data[key]['name'],
					desc =  data.data[key]['desc'];
				if(selectid==id){
					list += "<option value='"+id+"' desc='"+desc+"' selected='selected'>"+name+"</option>";
				}else{
					list += "<option value='"+id+"' desc='"+desc+"'>"+name+"</option>";
				}
			}
			list+="<select>";
			$(".venuelist").append(list);			
			$('#venueselect').change(function(){ //设置 venueid
				schedule.venueid = $(this).children('option:selected').val();
				schedule.venuedesc = $(this).children('option:selected').attr("desc");
			}); 
		}else{
			$(".venuelist").append("<span class='label'>没有场地信息,请录入后再选择场地</span>");
		}
	}
	
	var url = site.web+"my/"+site.venue+"/list";
	var json = {url:url,eid:id,uid:site.uid};
	G(json,cb);
}

getguest = function(gids){//guest
	if(!gids)return;
	cb = function (data){
		if(data.code==1){
			 schedule.gids = [];
			 schedule.guestbox = [];
			for(var key in data.data){
				var gid = data.data[key]["gid"],
					name = data.data[key]["name"];
				 schedule.gids.push(gid);
				 schedule.guestbox.push(name);
			}
			showguest();
		}
	}
	
	var url = site.web+"my/"+site.guest+"/getbyid";
	var json = {url:url,gids:gids,uid:site.uid};
	G(json,cb);
}

getsponsor = function(spids){//sponsor
	if(!spids)return;
	cb = function (data){
		if(data.code==1){
			 schedule.spids = [];
			 schedule.sponsorbox = [];
			for(var key in data.data){
				var spid = data.data[key]["spid"],
					cname = data.data[key]["cname"];
				 schedule.spids.push(spid);
				 schedule.sponsorbox.push(cname);
			}
			showsponsor();
		}
	}
	
	var url = site.web+"my/event"+site.sponsor+"/getbyid";
	var json = {url:url,spids:spids,uid:site.uid};
	G(json,cb);
}

showguest = function(){
	$(".guestlist").empty();
	if(schedule.guestbox.length==0){
		$(".guestlist").append('<span class="label">没有选择嘉宾</span>');
		return;
	}
	var glist = "";
	for(var key in schedule.guestbox){
		glist += "<span class='label margin5'>"+schedule.guestbox[key]+"</span>";
	}
	$(".guestlist").append(glist);
}

showsponsor = function(){
	$(".sponsorlist").empty();
	if(schedule.sponsorbox.length==0){
		$(".sponsorlist").append('<span class="label">没有选择赞助商</span>');
		return;
	}
	var glist = "";
	for(var key in schedule.sponsorbox){
		glist += "<span class='label margin5'>"+schedule.sponsorbox[key]+"</span>";
	}
	$(".sponsorlist").append(glist);
}


resetbox = function(arg){	
	fn = function(key){
		if(key=="guest"){
			schedule.gids = [];
			schedule.guestbox = [];
			$(".guestlist").empty();
			$(".guestlist").append("<span class='label'>没有选择嘉宾</span>");
			$(".guestdialogmsg").html("没有选择嘉宾");
		}		
		if(key=="sponsor"){
			schedule.spids = [];
			schedule.sponsorbox = [];	
			$(".sponsorlist").empty();
			$(".sponsorlist").append("<span class='label'>没有选择赞助商</span>");
			$(".sponsordialogmsg").html("没有选择赞助商");
		}
	}
	switch(arg){
		case "guest":
			fn(arg);
			break;
		case "sponsor":
			fn(arg);
			break;
		default:
			fn("guest");
			fn("sponsor");
			break;
	}
}

init_guest_dialog = function(){
	$(".canceldialog2").click(function(){//关闭dialog
		$('#myModal2').modal('hide');
		$('#myModal').modal('show');
	});
	
	$(".canceldialog3").click(function(){//关闭dialog
		$('#myModal3').modal('hide');
		$('#myModal').modal('show');
	});
	
	$("#open_guest_dialog").click(function(){//打开 guest dialog
		$(this).text("重新选择嘉宾");
		resetbox("guest");
		$(".guestselectlist").empty();
		cb = function (data){
			if(data.code==1){
				var list = "<ul class='guest-ul'>";
				for(var key in data.data){
					var id = data.data[key]['gid'],
						name = data.data[key]['name'];
					list += "<li class='guest-li margin5'><a class='btn guestitem' gid='"+id+"' title='"+name+"' select='0'>"+name+"</a></li>";
				}
				list+="</ul>";
				$(".guestselectlist").append(list);			
				
			}else{
				$(".guestselectlist").append("没有嘉宾信息,请录入后再进行选择");
			}
		}
		
		var url = site.web+"my/"+site.guest+"/list";
		var json = {url:url,uid:site.uid};
		G(json,cb);
		
		$('#myModal').modal('hide');
		$('#myModal2').modal('show');
	});
	
	$("#open_sponsor_dialog").click(function(){//打开 guest dialog
		$(this).text("重新选择赞助商");
		resetbox("sponsor");
		$(".sponsorselectlist").empty();
		cb = function (data){
			if(data.code==1){
				var list = "<ul class='sponsor-ul'>";
				for(var key in data.data){
					var id = data.data[key]['spid'],
						name = data.data[key]['cname'];
					list += "<li class='sponsor-li margin5'><a class='btn sponsoritem' spid='"+id+"' title='"+name+"' select='0'>"+name+"</a></li>";
				}
				list+="</ul>";
				$(".sponsorselectlist").append(list);				
			}else{
				$(".sponsorselectlist").append("没有赞助商信息,请录入后再进行选择");
			}
		}
		
		var url = site.web+"my/"+site.sponsor+"/list";
		var json = {url:url,uid:site.uid};
		G(json,cb);
		
		$('#myModal').modal('hide');
		$('#myModal3').modal('show');
	});
	
	$(".guestitem").live("click", function(){//select guest
		  var itemstatus = $(this).attr("select"),
		  	  gid = $(this).attr("gid"),
		  	  gname = $(this).text(),
		      cancel = "0",
		      select = "1",
		  	  key = itemstatus == cancel ? select  : cancel;
		  $(this).attr("select",key);
		  switch(key){
			  case select: 
				  schedule.gids.push(gid);
				  schedule.guestbox.push(gname);
				  break;
			  case cancel: 
				  schedule.gids.pop(gid);
				  schedule.guestbox.pop(gname);
				  break;
		  }
		 var msg = "已选择"+schedule.gids.length+"位嘉宾";
		 if(schedule.gids.length==0)msg = "没有选择嘉宾"; 
		 $(".guestdialogmsg").html(msg);
	});
	
	$(".sponsoritem").live("click", function(){//select sponsor
		  var itemstatus = $(this).attr("select"),
		  	  spid = $(this).attr("spid"),
		  	  cname = $(this).text(),
		      cancel = "0",
		      select = "1",
		  	  key = itemstatus == cancel ? select  : cancel;
		  $(this).attr("select",key);
		  switch(key){
			  case select: 
				  schedule.spids.push(spid);
				  schedule.sponsorbox.push(cname);
				  break;
			  case cancel: 
				  schedule.spids.pop(spid);
				  schedule.sponsorbox.pop(cname);
				  break;
		  }
		 var msg = "已选择"+schedule.spids.length+"位赞助商";
		 if(schedule.spids.length==0)msg = "没有选择赞助商"; 
		 $(".sponsordialogmsg").html(msg);
	});
	
	$("#guest_dialog_save").click(function(){//show guestlist
		showguest();
		$(".canceldialog2").click();
	});
	
	$("#sponsor_dialog_save").click(function(){//show sponsorlist
		showsponsor();
		$(".canceldialog3").click();
	});
	
	$("#cancel_guestlist").click(function(){//show guestlist
		resetbox("guest");
	});
	$("#cancel_sponsorlist").click(function(){//show sponsorlist
		resetbox("sponsor");
	});
}